package org.casaca.checkbackup.core.checksum;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.casaca.checkbackup.core.exception.ChecksumInitializeException;
import org.casaca.checkbackup.core.exception.ChecksumResetException;

public class SHA1Checksum extends Checksum {
	
	private MessageDigest md;
	private String checksum;

	public SHA1Checksum(String name, String shortname) throws ChecksumInitializeException {
		super(name, shortname);
		
		try {
			this.md = MessageDigest.getInstance("SHA1");
			this.checksum = null;
			
		} catch (NoSuchAlgorithmException e) {
			throw new ChecksumInitializeException(e);
		}
	}

	@Override
	public void addSlice(byte[] b, int offset, int len) {
		this.md.update(b, offset, len);
	}

	@Override
	public void complete() {
		byte[] b = this.md.digest();

		String result = "";
		for (int i=0;i<b.length;i++) {
			result +=
				Integer.toString((b[i]&0xff)+0x100, 16).substring(1);
		}
		this.checksum = result;
	}

	@Override
	public String getChecksum() {
		if(this.checksum==null)
			throw new IllegalStateException("Complete the process before getting the checksum");
		
		return this.checksum;
	}

	@Override
	public void reset() throws ChecksumResetException {
		try {
			this.md = MessageDigest.getInstance("SHA1");
			this.checksum = null;
			
		} catch (NoSuchAlgorithmException e) {
			throw new ChecksumResetException(e);
		}
	}

	@Override
	public String getChecksumType() {
		return "SHA1";
	}
}